﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Data;
using System.Web.UI.WebControls;

namespace Thksoft.Modal
{
    public partial class TradeBillEdit : BasePage
    {
        private YX_TradeBillBLL bbbll = new YX_TradeBillBLL();
        private Sys_UserBLL user = new Sys_UserBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtDateStart.Value = DateTime.Now.ToString("yyyy-MM-dd");

                BindBank();
                BindCompany();
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    BindData();
                }
            }
        }

        /// <summary>
        /// 修改绑定数据
        /// </summary>
        public void BindData()
        {
            string id = Request.QueryString["ID"].ToString();

            YX_TradeBill model = bbbll.SelectById(id);

            if (model != null)
            {
                FORM_BANK_ID.SelectedValue = model.N_TRADEBILL_DRAWERBANKID.ToString();
                FORM_COMPANY_ID.SelectedValue = model.N_TRADEBILL_DRAWERCMYID.ToString();
                //出票人
                BindUser(FORM_COMPANY_ID.SelectedValue);

                txtPayeeBank.Value = model.C_TRADEBILL_PAYEEBANKNAME.ToString();
                txtPayeeCompany.Value = model.C_TRADEBILL_PAYEECMYNAME.ToString();
                txtZnum.Value = model.C_TRADEBILL_DRAWERACCOUNT;
                txtDfzh.Value = model.C_TRADEBILL_PAYEEACCOUNT;
                txtamont1.Value = model.N_TRADEBILL_INVOICEVALUE.ToString();
                txtDateStart.Value = model.D_TRADEBILL_STARTDATE.ToString("yyyy-MM-dd");
                txtDateEnd.Value = model.D_TRADEBILL_ENDDATE.ToString("yyyy-MM-dd");
                txtBanknum.Text = model.C_TRADEBILL_CODE;
                ddlCheckType.SelectedValue = model.N_TRADEBILL_IFOFFER.ToString();
                txtRemark.Text = model.C_TRADEBILL_REMARK;
                txtPayee.Value = model.C_TRADEBILL_PAYEENAME.ToString();
                txtPayerName.Value = model.C_TRADEBILL_PAYERNAME.ToString();

                //txtDrawer.Value = user.Find(model.N_TRADEBILL_DRAWERID).USER_NAME.ToString();
                FORM_Drawer.Text = model.N_TRADEBILL_DRAWERID.ToString();
            }
        }

        #region 初次加载公司和银行

        /// <summary>
        /// 得到汇票银行
        /// </summary>
        public void BindBank()
        {
            int count;

            var dt = new Sys_BankBLL().GetEntitys(null, null, 0, 1000, out count);

            FORM_BANK_ID.DataSource = dt;
            FORM_BANK_ID.DataTextField = "C_NAME";
            FORM_BANK_ID.DataValueField = "N_ID";
            FORM_BANK_ID.DataBind();
            FORM_BANK_ID.Items.Insert(0, new ListItem("---请选择---", "-1"));

            FORM_BANK_ID.SelectedValue = "-1";
        }

        /// <summary>
        /// 得到汇票公司
        /// </summary>
        public void BindCompany()
        {
            int count;

            string whereStr = @" CMY_ID in (select cp.cmy_id
  from sys_company cp
 start with cp.cmy_id = " + lognUser.USER_COMPANY + @"
connect by prior cp.cmy_id = cp.cmy_parentid) ";

            var dt = new Sys_CompanyBLL().GetEntitys(whereStr, null, 0, 1000, out count);

            FORM_COMPANY_ID.DataSource = dt;
            FORM_COMPANY_ID.DataTextField = "CMY_NAME";
            FORM_COMPANY_ID.DataValueField = "CMY_ID";
            FORM_COMPANY_ID.DataBind();
            FORM_COMPANY_ID.Items.Insert(0, new ListItem("---请选择---", "-1"));

            FORM_COMPANY_ID.SelectedValue = "-1";
        }

        /// <summary>
        /// 根据公司ID得到用户
        /// </summary>
        /// <param name="cmyId"></param>
        public void BindUser(string cmyId)
        {
            var dt = user.GetNameByCmyId(cmyId);
            this.FORM_Drawer.DataSource = dt;
            this.FORM_Drawer.DataTextField = "user_name";
            this.FORM_Drawer.DataValueField = "user_id";
            this.FORM_Drawer.DataBind();
        }

        #endregion 初次加载公司和银行

        protected void btnSave_Click(object sender, EventArgs e)
        {
            #region 编辑条件

            if (FORM_COMPANY_ID.SelectedValue.ToString() == "-1")
            {
                MessageBox.Show(Page, "请选择出票人公司名称");
                return;
            }
            if (FORM_BANK_ID.SelectedValue.ToString() == "-1")
            {
                MessageBox.Show(Page, "请选择出票人银行名称");
                return;
            }
            if (txtZnum.Value.Trim() == "")
            {
                MessageBox.Show(Page, "出票人账号不能为空");
                return;
            }
            if (txtBanknum.Text.Trim() == "")
            {
                MessageBox.Show(Page, "交易合同号不能为空");
                return;
            }
            if (txtDfzh.Value.Trim() == "")
            {
                MessageBox.Show(Page, "收款人账号不能为空");
                return;
            }
            if (txtPayeeCompany.Value.Trim() == "")
            {
                MessageBox.Show(Page, "收款人公司名称不能为空");
                return;
            }
            if (txtPayeeBank.Value.Trim() == "")
            {
                MessageBox.Show(Page, "收款人银行名称不能为空");
                return;
            }
            if (txtamont1.Value.Trim() == "")
            {
                MessageBox.Show(Page, "出票金额不能为空");
                return;
            }
            else
            {
                decimal je = 0;
                if (!decimal.TryParse(txtamont1.Value.Trim(), out je))
                {
                    MessageBox.Show(Page, "出票金额必须是数字");
                    return;
                }
                else
                {
                    if (Convert.ToDecimal(txtamont1.Value.Trim()) > 10000000)
                    {
                        MessageBox.Show(Page, "票面金额最高为1000万元");
                        return;
                    }
                }
            }

            if (txtDateStart.Value.Trim() == "")
            {
                MessageBox.Show(Page, "出票日期不能为空");
                return;
            }

            if (txtDateEnd.Value.Trim() == "")
            {
                MessageBox.Show(Page, "最后期限不能为空");
                return;
            }

            //if (txtDrawer.Value.Trim() == "")
            //{
            //    MessageBox.Show(Page, "出票人不能为空");
            //    return;
            //}

            if (txtPayee.Value.Trim() == "")
            {
                MessageBox.Show(Page, "收款人不能为空");
                return;
            }

            if (txtPayerName.Value.Trim() == "")
            {
                MessageBox.Show(Page, "持票人不能为空");
                return;
            }

            bool mainName = SelectMethod();
            if (mainName == false)
            {
                MessageBox.Show(Page, "主账户要与银行账户设置相匹配,且必须为支出户!");
                return;
            }

            #endregion 编辑条件

            YX_TradeBill model = new YX_TradeBill();

            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                //修改
                string id = Request.QueryString["ID"].ToString();

                model = bbbll.SelectById(id);
            }
            else
            {
                model.N_TRADEBILL_ID = 1;
            }

            model.D_TRADEBILL_STARTDATE = DateTime.Parse(txtDateStart.Value);
            model.D_TRADEBILL_ENDDATE = DateTime.Parse(txtDateEnd.Value);
            model.N_TRADEBILL_DRAWERBANKID = decimal.Parse(FORM_BANK_ID.SelectedValue);
            model.N_TRADEBILL_DRAWERCMYID = decimal.Parse(FORM_COMPANY_ID.SelectedValue);
            model.C_TRADEBILL_PAYEEBANKNAME = txtPayeeBank.Value.Trim();
            model.C_TRADEBILL_PAYEECMYNAME = txtPayeeCompany.Value.Trim();
            model.C_TRADEBILL_DRAWERACCOUNT = txtZnum.Value.Trim();
            model.C_TRADEBILL_PAYEEACCOUNT = txtDfzh.Value.Trim();
            model.N_TRADEBILL_INVOICEVALUE = decimal.Parse(txtamont1.Value);
            model.C_TRADEBILL_CODE = txtBanknum.Text.Trim();
            model.C_TRADEBILL_REMARK = txtRemark.Text.Trim();
            model.N_TRADEBILL_IFOFFER = decimal.Parse(ddlCheckType.SelectedValue);
            model.C_TRADEBILL_PAYERNAME = txtPayerName.Value.Trim();
            model.C_TRADEBILL_PAYEENAME = txtPayee.Value.Trim();
            model.N_TRADEBILL_DRAWERID = Convert.ToDecimal(FORM_Drawer.Text);
            //string sql = string.Format(@"select * from sys_user where user_name = '{0}' and user_company={1}", FORM_Drawer.Text.Trim(), decimal.Parse(FORM_COMPANY_ID.SelectedValue));
            //var username=user.FirstOrDefaultQuery(sql);
            //if (username != null)
            //{
            //    model.N_TRADEBILL_DRAWERID = decimal.Parse(username["USER_ID"].ToString());
            //}
            //else
            //{
            //    MessageBox.Show(Page, "本公司没有此出票人！");
            //    return;
            //}

            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                //修改
                int count = bbbll.UPDATE(model, lognUser.USER_NAME);

                if (count > 0)
                {
                    MessageBox.Show(Page, "修改成功！");
                }
                else
                {
                    MessageBox.Show(Page, "修改失败！");
                }
            }
            else
            {
                //新增
                int count = bbbll.INSERT(model, lognUser.USER_NAME);
                YX_BillsLedger ledger = new YX_BillsLedger();
                ledger.N_BILL_ID = model.N_TRADEBILL_ID;
                ledger.N_TYPE = 1;
                var billall = new BankBillsLedgerBLL().Insert(ledger, CurrentUserName);

                if (count > 0)
                {
                    MessageBox.Show(Page, "新增成功！");
                }
                else
                {
                    MessageBox.Show(Page, "新增失败！");
                }
            }
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            MessageBox.ResponseScript(this, "FORM_CLOSE();");
        }

        /// <summary>
        /// 根据输入的主账号查询银行账户设置的主账号
        /// </summary>
        private bool SelectMethod()
        {
            BaseBLL bsBLL = new BaseBLL();
            DataTable dt = null;
            string mainName = this.txtZnum.Value.ToString();

            string sql = " and a.accountno = '" + mainName + "'";

            {
                string _sql = @"select a.accounti_id accountId,
       c.cmy_name companyName,
       d.deptname depName,
       decode(a.accounttype, 1, '支出户', 2, '收入户') accType,
       a.accountno accountNo,
       b.c_name openBank
  from sys_company c, sys_department d, yx_account a,sys_bank b
 where c.cmy_id = d.cmy_id
   and c.cmy_id = a.company_id
   and d.deptid = a.department_id
   and a.n_bank_id=b.n_id
   and a.accounttype=1 ";
                if (_sql != "")
                {
                    _sql += sql;
                }
                dt = bsBLL.Query(_sql);
            }

            if (dt.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        protected void FORM_COMPANY_ID_SelectedIndexChanged(object sender, EventArgs e)
        {
            string cmyId = FORM_COMPANY_ID.SelectedValue.ToString();
            BindUser(cmyId);
        }
    }
}